#include "mainwindow.h"
#include "pub_var.h"
#include "com_dialog_signin.h"
#include <QMessageBox>
#include <QApplication>
#include <QDebug>
#include <QDateTime>
#include <QMutex>
#include <QTextCodec>
#include <QDir>
#include <QSharedMemory>
#include <QSettings>

QSharedMemory share;
int MAX_SQL_LENGTH; //sql语句最大允许长度

void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("Debug:");
        break;

    case QtWarningMsg:
        text = QString("Warning:");
        break;

    case QtCriticalMsg:
        text = QString("Critical:");
        break;

    case QtFatalMsg:
        text = QString("Fatal:");
        break;
    default:
        text = QString("Debug:");
        break;

    }

    QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
    //QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString current_date_time = QDateTime::currentDateTime().toString("hh:mm:ss");
    QString current_date = QString("(%1)").arg(current_date_time);
    QString message = QString("%1 %2 %3 %4").arg(current_date).arg(text).arg(context_info).arg(msg);

    QString fileName = "logs/" + QDate::currentDate().toString("yyyyMMdd") + ".log";

    QFile file(fileName);
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream << message << "\r\n";
    file.flush();
    file.close();

    mutex.unlock();
}


int main(int argc, char *argv[])
{

     MAX_SQL_LENGTH = 100000; //sql语句最大允许长度

    //注册MessageHandler
    qInstallMessageHandler(outputMessage);

    QApplication a(argc, argv);
    // utf8/gbk/gb18030;
    //不用gb18030，有些医保交易会出现乱码
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("gb18030")) ;

    pub::base_path = QCoreApplication::applicationDirPath();

    //查看基础路径是否存在，如不存在则建立
    //日志文件
    QString basePath = pub::base_path + "/logs/upload";

    QDir d = QDir(basePath);
    if(!d.exists()){
        d.mkdir(basePath);
    }

    basePath = pub::base_path + "/logs";
    d = QDir(basePath);
    if(!d.exists()){
        d.mkdir(basePath);

    }
    else
    {
        //保留最近30次日志文件
        d.setNameFilters( QStringList("*.log") );
        d.setSorting(QDir::Name);   //sorted by name, reversed.
        d.setSorting(QDir::Reversed);
        QStringList files = d.entryList();  //read filenames

        for(int i = 30; i < files.size() ; i++){
            QFile f(basePath + "/" + files[i]);
            f.remove();
        }

    }

    //下载路径
    basePath = pub::base_path + "/download";
    d = QDir(basePath);
    if(!d.exists()){
        d.mkdir(basePath);
    }

    //下载文件归档路径
    basePath.append("/back");
    d = QDir(basePath);
    if(!d.exists()){
        d.mkdir(basePath);
    }

    //本机工作模式
    QSettings setIni("clin.ini", QSettings::IniFormat);
    pub::DEBUG = (setIni.value("system/debug").toString() == "1" ? true : false);

    if(!pub::DEBUG)
    {
        //正常运行模式，通过共享内存控制程序单例运行

        share.setKey("_clinic_rensheng_");

        //测试共享内存是否存在，存在则赋值然后退出
        if(share.attach())
        {
            QMessageBox::warning(NULL, "注意", "应用程序正在运行，无法重复启动！");
            return 0;
        }
        else
        {
            //创建共享内存
            if(!share.create(1))
            {
                QMessageBox::warning(NULL, "注意", "无法创建共享内存，程序启动失败！");
                return 0;
            }
            else
            {
                if(share.lock())
                {
                    char * d = (char *)share.data();
                    *d = '0';
                    share.unlock();
                }
                else
                {
                    QMessageBox::warning(NULL, "注意", "无法锁定共享内存，程序启动失败！");
                    return 0;
                }
            }
        }
    }


    //装入样式表

    QFile qssFile(":/style1.css");

    if(qssFile.open(QFile::ReadOnly)){

        QString qss = QString::fromLatin1(qssFile.readAll());

        int ftsz = setIni.value("system/fontSize").toInt();
        if( ftsz >= 10 && ftsz<=20 )
        {

            QString tmp = "font-size:" + QString::number(ftsz) + "px";
            qss.replace(qss.indexOf("font-size:"), 14, tmp);

        }
        QString qs;
        QTextCodec *codec = QTextCodec::codecForName("GBK");

        qs=QString(codec->fromUnicode(qss));

        qApp->setStyleSheet(qs);							//整个app都使用此样式表
        qssFile.close();

    }


    //数据库连接
    QString host,port,dbnm, usr, pswd;

    //MYSQL数据库
    host = setIni.value("database/m_hostname").toString();
    port = setIni.value("database/m_port").toString();
    dbnm = setIni.value("database/m_databasename").toString();
    usr = setIni.value("database/m_username").toString();
    pswd = setIni.value("database/m_password").toString();

    pub::db_m.setPort(port.toInt());
    pub::db_m.setHostName(host);
    pub::db_m.setPassword(pswd);
    pub::db_m.setUserName(usr);
    pub::db_m.setDatabaseName(dbnm);
    pub::db_m.setConnectOptions("MYSQL_OPT_CONNECT_TIMEOUT=10");
    if(!pub::db_m.open()){
        QString tmp = "Can not open database ！ \nPort: "+port;
        tmp = tmp + "\nHost: "+host;
        tmp = tmp + "\nDBName: "+dbnm;
        QMessageBox::information(NULL,"注意",tmp);
        return 0;
    }

    //ORACLE数据库
    host = setIni.value("database/o_hostname").toString();
    port = setIni.value("database/o_port").toString();
    dbnm = setIni.value("database/o_databasename").toString();
    usr = setIni.value("database/o_username").toString();
    pswd = setIni.value("database/o_password").toString();
    pub::db_o.setPort(port.toInt());
    pub::db_o.setHostName(host);
    pub::db_o.setPassword(pswd);
    pub::db_o.setUserName(usr);
    pub::db_o.setDatabaseName(dbnm);
    if(!pub::db_o.open()){
        QString tmp = "Can not open database ！ \nPort: "+port;
        tmp = tmp + "\nHost: "+host;
        tmp = tmp + "\nDBName: "+dbnm;

        QMessageBox::information(NULL,"注意",tmp);
        return 0;
    }


    //用户登录
    Dialog_signin sign;
    sign.exec();
    if(!pub::userValidated){
        //用户验证失败，直接退出
        return 0;
    }

    //用户验证通过，打开主窗口
    MainWindow w;
    w.show();
    return a.exec();
}
